package com.ruis.kotboot.common.util

import java.io.*

/**
 * Created by mgr on 2018/3/14.
 */

object IOUtil{
    fun getExtion(name:String):String?{
        try{
            val ind=name.lastIndexOf(".")
            if(ind>0&&ind<name.length-1)
                return name.substring(ind+1,name.length)
        }catch (e:Exception){}
        return null
    }

    fun file2str(fl: File):String{
        val bf = BufferedReader(FileReader(fl))
        val sb = StringBuilder()
        var content = ""
        while(true){
            try {
                content = bf.readLine()
                if (content == null) break
                sb.append(content.trim())
            }catch (e:Exception){break}
        }
        bf.close()
        return sb.toString()
    }

    fun str2file(fl:File,str:String){
        val bw = BufferedWriter(FileWriter(fl))
        bw.write(str)
        bw.close()
    }
    fun strAp2file(fl:File,str:String){
        val pw = PrintWriter(FileWriter(fl))
        pw.println(str)
        pw.flush()
        pw.close()
    }

    private val FILESIZE_G=1024*1024*1024.toFloat()
    private val FILESIZE_M=1024*1024.toFloat()
    private val FILESIZE_K=1024.toFloat()

    fun getFilesizes(sz:Long?):String{
        if(sz==null||sz<=0)return "0 K"
        if (sz>FILESIZE_G)
            return "${(sz/FILESIZE_G*100).toInt()/100.toFloat()} G"
        if (sz>FILESIZE_M)
            return "${(sz/FILESIZE_M*100).toInt()/100.toFloat()} M"
        if (sz>FILESIZE_K)
            return "${(sz/FILESIZE_K*100).toInt()/100.toFloat()} K"
        return "0 K"
    }
}